package com.linciping.useges.plugin.util;

import com.android.SdkConstants;
import com.android.tools.idea.AndroidPsiUtils;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import org.jetbrains.android.facet.AndroidFacet;
import org.jetbrains.android.facet.SourceProviderManager;
import org.jetbrains.android.dom.manifest.AndroidManifestXmlFile;

public class AndroidUtil {

    public static AndroidManifestXmlFile getModuleAndroidManifestXmlFile(Module module) {
        AndroidFacet androidFacet = AndroidFacet.getInstance(module);
        VirtualFile virtualFile = SourceProviderManager.getInstance(androidFacet).getMainManifestFile();
        if (virtualFile == null) return null;
        PsiFile psiFile = AndroidPsiUtils.getPsiFileSafely(module.getProject(), virtualFile);
        if (psiFile instanceof XmlFile) {
            XmlFile xmlFile = (XmlFile) psiFile;
            XmlTag rootTag = xmlFile.getRootTag();
            if (rootTag != null && rootTag.getName().equals(SdkConstants.TAG_MANIFEST)) {
                return new AndroidManifestXmlFile(xmlFile);
            }
        }
        return null;
    }
}
